/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var HOME='home';
var ENTITY_USER='user';
var ENTITY_PRODUCT='product';
var ENTITY_POSITION='position';
var ENTITY_PHOTO='photo';
var ENTITY_VIEWTYPE='viewType';
var ENTITY_RELATIONSHIP='relationship';

//get base URL
var ROOT_URL=getBaseURL();

//function to initialize the page
var init = function() {
	//showing the home tab on initializing
	showTab(HOME);
	//adding event listeners to the tabs
	$('#tabs a').click(function(event) {
		showTab(event.currentTarget.id);
	});
}

//function to show the tab
var showTab = function(entity) {
	//remove the active class from all the tabs
	$('.tab').removeClass("active");
	//setting the active class to the selected tab
	$('#'+entity).addClass("active");
	//hiding all the tabs
	$('.g-unit').hide();
	//showing the selected tab
	$('#' + entity + '-tab').show();
	//hiding the message block
	$('.message').hide();
	//hiding the create block
	showHideCreate(entity, false);
	if(entity!=HOME)
		$('#'+entity+'-search-reset').click();
}

//function to show/hide create block for an entity in a tab 
var showHideCreate = function(entity, show) {
	//checking if the block is show or not
	if (show) {
		//hiding the search container
		$('#' + entity + '-search-ctr').hide();
		//hiding the list container
		$('#' + entity + '-list-ctr').hide();
		//showing the create container
		$('#' + entity + '-create-ctr').show();
		
	} else {
		//showing the search container
		$('#' + entity + '-search-ctr').show();
		//showing the list container
		$('#' + entity + '-list-ctr').show();
		//hiding the create container
		$('#' + entity + '-create-ctr').hide();
		//checking if the entity is not a home then populating the list of the entity
		if(entity!=HOME)
			populateList(entity,null);
	}
}

//parameter object definition
var param=function(name,value){
	this.name=name;
	this.value=value;
}

//function to add an entity when user clicks on the add button in UI
var add = function(entity) {
	$('.message').hide();
	$('#'+entity+'-reset').click();
	//display the create container
	showHideCreate(entity, true);
	$("span.readonly input").attr('readonly', false);
	$("select[id$=photo-user-list] > option").remove();
	$("select[id$=position-user-list] > option").remove();
	//checking the entity to populate the select box
	if (entity == ENTITY_POSITION) {
		//populating the user and contact by making an ajax call
		populateSelectBox('position-user-list', '/user');
	}  else if (entity == ENTITY_PHOTO){
		//populating the user and photo by making an ajax call
		populateSelectBox('photo-user-list','/user');
		//populateSelectBox('order-position-list','/position');
	} 
}

//function to search an entity when user inputs the value in the search box
var search = function(entity) {
	$('.message').hide();
	// collecting the field values from the form
	 var formEleList = $('form#'+entity+'-search-form').serializeArray();
	 //assigning the filter criteria
	 var filterParam=new Array();
	 for(var i=0;i<formEleList.length;i++){
		 filterParam[filterParam.length]=new param(formEleList[i].name,formEleList[i].value); 
	 }
	 //calling population of the list through ajax
	 populateList(entity,filterParam);
}

var showMessage = function(message, entity){
	$('#'+entity+'-show-message').show().html('<p><b>'+message+'</b></p>');
}

var formValidate = function(entity){
	var key;
	var formEleList = $('form#'+entity+'-create-form').serializeArray();
	key=formEleList[0].value;
	switch(entity){
		case ENTITY_POSITION:
			var valueUser = $('#position-user-list').val();
			if(valueUser == "" || formEleList[0].value == "" || formEleList[1].value == ""){
				showMessage('please check the Latitude, Longitude and User values in the form', entity);
				return;
			}
			if (isDecimal(formEleList[0].value) == false || isDecimal(formEleList[1].value) == false) {
				showMessage('Latitude and Longitude values must be decimal type', entity);
			}
			break;
		case ENTITY_USER:
			var hasError = false;
		    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		    var emailaddressVal = $("#email").val();
		    if(emailaddressVal == '' || !emailReg.test(emailaddressVal)|| key== "") {
		      hasError = true;
		    }
		    if (!isPhoneNumber(formEleList[0].value)) {
		    	showMessage('Phone number is not correct the format, please check it again', entity);
			}
		    if(hasError == true){
		    	showMessage('please check the name and email values in the form', entity);
				return;
		    }
			break;
		case ENTITY_PHOTO:
			var valueUser = $('#photo-user-list').val();
			if(valueUser == "" || formEleList[0].value == "" || formEleList[1].value == ""){
				showMessage('please check the Title, Caption and User values in the form', entity);
				return;
			}
			if (!window.FileReader) {
				showMessage('The file API isn\'t supported on this browser yet.', entity);
		        return;
		    }
			var input = document.getElementById('fileupload');
			if (!input) {
				showMessage('Um, couldn\'t find the fileinput element.', entity);
		    }
		    else if (!input.files) {
		    	showMessage('This browser doesn\'t seem to support the `files` property of file inputs.', entity);
		    }
		    else if (!input.files[0]) {
		    	showMessage('Please select a file before clicking \'Save\'', entity);
		    }
		    else {
		        file = input.files[0];
		        if (file.size/1024/1024 > 1)
		        	showMessage('File ' + file.name + ' is ' + file.size + ' bytes in size. It is more than 1M', entity);
		    }
			break;
		case ENTITY_VIEWTYPE:
			var viewType = $("#viewTypeName").val();
			if (viewType == null || viewType == "") {
				showMessage('Name is not empty', entity);
				return;
			}
		case ENTITY_RELATIONSHIP:
			var viewType = $("#relationshipName").val();
			if (viewType == null || viewType == "") {
				showMessage('Name is not empty', entity);
				return;
			}	
		default :
			if(key==""){
				showMessage('please check the values in the form', entity);
				return;
			}
			break;
	}
	save(entity);
	$('#'+entity+'-show-message').hide();
}

//function to save an entity
var save = function(entity) {
		// creating the data object to be sent to backend
	 var data=new Array();
	// collecting the field values from the form
	 var formEleList = $('form#'+entity+'-create-form').serializeArray();
	 for(var i=0;i<formEleList.length;i++){
		data[data.length]=new param(formEleList[i].name,formEleList[i].value);
	 }
	 if (entity == ENTITY_PHOTO) {
		 var reader, file;
		 file = document.getElementById('fileupload').files[0];
		 
		 if (!!file.type.match(/image.*/)) {
				if ( window.FileReader ) {
					reader = new FileReader();
//					reader.onloadend = function (e) { 
//						showUploadedItem(e.target.result, file.fileName);
//					};
					reader.readAsDataURL(file);
				}
				if (data) {
					data[data.length]=new param('file',file);
					data[data.length]=new param('contentType',file.type);
				}
			}	
		 
	 }
		 
	 //setting action as PUT
	 data[data.length]=new param('action','PUT');
	 //making the ajax call
	 $.ajax({
			url : "/"+entity,
			type : "POST",
			data:data,
			success : function(data) {
				showHideCreate(entity,false);
			}
		});
	 $('#'+entity+'-reset').click();
}

//function to edit entity
var edit = function(entity, id){
	var parameter=new Array();
	parameter[parameter.length]=new param('q',id);
	$.ajax({
		url : "/"+entity,
		type : "GET",
		data:parameter,
		success : function(resp) {
			var data=resp.data[0];
			var formElements = $('form#'+entity+'-create-form :input');
			for(var i=0;i<formElements.length;i++){
				if(formElements[i].type !="button"){
					var ele=$(formElements[i]);
					if(ele.attr('name')=="user"){
						$("select[id$=position-user-list] > option").remove();
						ele.append('<option value="'+eval('data.'+ele.attr('name'))+'">'+eval('data.'+ele.attr('name'))+'</option>');	
					}
					else
						ele.val(eval('data.'+ele.attr('name')));
				}
			}
			showHideCreate(entity, true);
			$("span.readonly input").attr('readonly', true);
		}
	});
}

//function called when user clicks on the cancel button
var cancel = function(entity) {
	$('.message').hide();
	//hiding the create container in the tab
	showHideCreate(entity, false);
}

//function to delete an entity
var deleteEntity = function(entity,id,parentid) {
	var parameter=new Array();
	parameter[parameter.length]=new param('id',id);
	parameter[parameter.length]=new param('parentid', parentid);
	parameter[parameter.length]=new param('action','DELETE');
	//making the ajax call
	$.ajax({
			url : "/"+entity,
			type : "POST",
			data:parameter,
			dataType:"html",
			success : function(resp) {
				showHideCreate(entity,false);
				if (resp!=''){
					showMessage(resp, entity);
				}
				
			},
			error : function(resp){
				showMessage(resp, entity);
			}
	});
}

// function to get the data by setting url, filter, success function and error function
var getData=function(url,filterData,successFn,errorFn){
	// making the ajax call
	$.ajax({
		url : url,
		type : "GET",
		data:filterData,
		success : function(resp) {
			//calling the user defined success function
			if(successFn)
			successFn(resp);	
		},
	error:function(e){
		//calling the user defined error function
		if(errorFn)
		 errorFn(e);
	}
	});
}

//function to populate the select box which takes input as id of the selectbox element and url to get the data
var populateSelectBox = function(id, url) {
	//specifying the success function. When the ajax response is successful then the following function will be called
	var successFn=function(resp){
		//getting the select box element
		var selectBox=$('#'+id);
		//setting the content inside as empty
		selectBox.innerHTML = '';
		//getting the data from the response object
		var data=resp.data; 
		//appending the first option as select to the select box
		selectBox.append('<option value="">Select</option>');
		//adding all other values
		for (var i=0;i<data.length;i++) {
			selectBox.append('<option value="'+data[i].name+'">'+data[i].name+'</option>');
		}
	}
	//calling the getData function with the success function
	getData(url,null,successFn,null);
}

//function to populate the list of an entity
var populateList=function(entity, filter){
	//specifying the success function. When the ajax response is successful then the following function will be called

	var successFn=function(resp){
		var data='';
		if(resp){
			//getting the data from the response object
			data=resp.data;
		}
		//creating the html content
		var htm='';
		if(data.length > 0){
			for (var i=0;i<data.length;i++){
				//creating a row
				htm+='<tr>';
				switch(entity)
				{
				
				case ENTITY_POSITION:
					htm+='<td>'+(i+1)+'</td>'+
						'<td>'+data[i].name+'</td>'+
						'<td>'+data[i].located+'</td>'+
						'<td>'+data[i].located_time+'</td>';
					break;
				
				case ENTITY_USER:
					htm+='<td>'+(i+1)+'</td>' +
					'<td>'+data[i].name+'</td>' + 
					'<td>'+data[i].fullname+'</td>' +
					'<td>'+data[i].link+'</td>' +
					'<td>'+data[i].birthday+'</td>'+
					'<td>'+data[i].interested_in+'</td>' +
					'<td><img width=\'50\' src=\'http://graph.facebook.com/'+data[i].name+'/picture\'/></td>' +
					'<td>'+data[i].gender+'</td>'+
					'<td>'+data[i].relationship_status+'</td>'+
					'<td>'+data[i].timezone+'</td>'+
					'<td>'+data[i].locale+'</td>'+
					'<td>'+data[i].verified+'</td>'+
					'<td>'+data[i].email+'</td>'+
					'<td>'+data[i].located+'</td>'+
					'<td>'+data[i].located_time+'</td>'+
					'<td>'+data[i].username+'</td>';
					break;
				case ENTITY_PHOTO:
					htm+='<td>'+data[i].name+'</td><td>'+data[i].title+'</td><td>'+data[i].caption+'</td><td>'+data[i].contentType+'</td><td><img width=\'50\' src=\''+ROOT_URL+'photo?action=display&id='+data[i].name+'&userId='+data[i].userId+'\'/></td>';
					break;
				case ENTITY_VIEWTYPE:
					htm+='<td>'+data[i].name+'</td>';
					break;	
				case ENTITY_RELATIONSHIP:
					htm+='<td>'+data[i].name+'</td>';
					break;		
				default:
					htm+=""; 
				}
				if(entity == ENTITY_USER)
					htm+='<td><a href="#" class="delete-entity" onclick=\'deleteEntity("'+entity+'","'+data[i].name+'",null)\'>Delete</a> | <a href="#" class="edit-entity" onclick=\'edit("'+entity+'","'+data[i].name+'")\'>Edit</a></td></tr>';
				else
					htm+='<td><a href="#" class="delete-entity" onclick=\'deleteEntity("'+entity+'","'+data[i].name+'","'+data[i].userId+'")\'>Delete</a></td></tr>';
			}
		}
		else{
			//condition to show message when data is not available
			var thElesLength=$('#'+entity+'-list-ctr table thead th').length;
			htm+='<tr><td colspan="'+thElesLength+'">No records found</td></tr>';
		}
		$('#'+entity+'-list-tbody').html(htm);
	}
	getData("/"+entity,filter,successFn,null);
}

// determine input is decimal

var isDecimal = function(input) {
	var decimal = /^[-+]?[0-9]+\.[0-9]+$/;
	if (input.match(decimal)) {
		return true;
	} else {
		return false;
	}
}   

// determine input is phone number 
var isPhoneNumber = function(input) {
	var phoneRe = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
	var digits = input.replace(/\D/g, "");
	return (digits.match(phoneRe) !== null);
}

var uploadImage = function(entity) {
	var formdata = new FormData();
	var formEleList = $('form#'+entity+'-create-form').serializeArray();
	 for(var i=0;i<formEleList.length;i++){
		 formdata.append(formEleList[i].name,formEleList[i].value);
	 }
	 
    var file = document.getElementById("fileupload").files[0];


    formdata.append("file", file);
    
    formdata.append("action", "PUT")

    var xhr = new XMLHttpRequest();       

    xhr.open("POST","/"+entity, true);

    xhr.send(formdata);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	showHideCreate(entity,false);
           $('#'+entity+'-reset').click();
        }
    }; 
    
    $('#'+entity+'-show-message').hide();
    
}

function getBaseURL () {
	   return location.protocol + "//" + location.hostname + 
	      (location.port && ":" + location.port) + "/";
	}

//Validates Date
var isValidDate = function(date) {
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[1];
    var m = matches[2]-1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
           composedDate.getMonth() == m &&
           composedDate.getFullYear() == y;
}

var isValidEmail = function(email) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	return emailReg.test(email);
}

var isValidPhone = function(phone) {
	var phoneRe = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
	var digits = phone.replace(/\D/g, "");
	return (digits.match(phoneRe) !== null);
}

//Update profile
var updateProfile = function(){
	// creating the data object to be sent to backend
	 var data=new Array();
	// collecting the field values from the form
	 var formEleList = $('form#user-update-form').serializeArray();
	 for(var i=0;i<formEleList.length;i++){
		data[data.length]=new param(formEleList[i].name,formEleList[i].value);
	 }
		 
	 //setting action as PUT
	 data[data.length]=new param('action','UPDATE');
	 //making the ajax call
	 $.ajax({
			url : "/user",
			type : "POST",
			data:data,
			success : function(data) {
				//showHideCreate(entity,false);
				showMessage('Successfully updated', 'user');
			}
		});
	
}

//Validates form update profile
var validateProfile = function() {
	var message = '';
	var hasError = false;
    
    //validate birthday
    var birthday = $("#birthdate").val() + '/' + $("#birthyear").val();
    birthday = birthday.trim();
    if (birthday.length > 2) {
    	if (!isValidDate(birthday)) {
    		hasError = true;
    		message += 'Invalid birthday </br>';
    	}
	}
    
    if ($("#email").val() != '' && $("#email").val() != null) {
		if (!isValidEmail($("#email").val())) {
			hasError = true;
    		message += 'Invalid email </br>';
		}
	}
    
    if ($("#mobilePhone").val() != '' && $("#mobilePhone").val() != null) {
    	if (!isValidPhone($("#mobilePhone").val())) {
			hasError = true;
    		message += 'Invalid mobile phone </br>';
		}
	}
    
    if(hasError == true){    	
    	showMessage(message, 'user');
		return;
    }
    updateProfile('user');
	$('#user-show-message').hide();
}







